package cn.dgut.FrontManger;

import cn.dgut.Utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        List<String> list = new ArrayList<>();

        for (Iterator iter = parameterMap.entrySet().iterator(); iter.hasNext(); ) {
            Map.Entry element = (Map.Entry) iter.next();
            String[] value = (String[]) element.getValue();
            for (int i = 0; i < value.length; i++) {
                list.add(value[i]);
            }
        }

        int flag = 1;

        String rightCoder = (String) request.getSession().getAttribute("coder");
        if(list.get(4).trim().toLowerCase().equals(rightCoder.toLowerCase())){
            String sql = "INSERT INTO `Student` VALUES (null,'"+list.get(0)+"', '"+list.get(1)+"','"+list.get(2)+"', '"+list.get(3)+"', 'default.png','no','未完善');";
            int count = new JDBCUtils().querySQL(sql);
            if(count==1){
                flag = 0;
            }
        }else {
            flag = 2;
        }

        response.setContentType("application/json,charset=utf-8");
        String strJson = "{\"flag\":\""+flag+"\"}";
        response.getWriter().println(strJson);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}